package ldh.maker.code;

import javafx.scene.control.TreeItem;
import ldh.database.Table;
import ldh.maker.database.TableInfo;
import ldh.maker.freemaker.ControllerMaker;
import ldh.maker.util.CopyDirUtil;
import ldh.maker.util.DbInfoFactory;
import ldh.maker.util.FileUtil;
import ldh.maker.util.FreeMakerUtil;
import ldh.maker.vo.SettingData;
import ldh.maker.vo.TreeNode;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by ldh on 2017/4/6.
 */
public class MobileCreateCode extends CreateCode {

    private volatile boolean isCreateMainPage = false;

    public MobileCreateCode(SettingData data, TreeItem<TreeNode> treeItem, String dbName, Table table) {
        super(data, treeItem, dbName, table);
    }

    @Override
    protected void createOther(){
        if (table.isMiddle()) return;
        String controllerPath = createPath(data.getControllerPackageProperty());
        String beanName = FreeMakerUtil.firstUpper(table.getJavaName());
        String jspPath = createJspPath();
        String jsPath = createJsPath();
        new ControllerMaker()
                .pack(data.getControllerPackageProperty())
                .outPath(controllerPath)
                .dbName(dbName)
                .treeId(treeItem.getParent().getValue().getId())
                .className(beanName + "Controller")
                .beanMaker(pojoMaker)
                .beanWhereMaker(pojoWhereMaker)
                .service(serviceInterfaceMaker)
                .imports(pojoWhereMaker)
                .table(table)
                .make();

        mainPage(jspPath);

        List<String> dirs = new ArrayList<>(Arrays.asList("code", root, this.getProjectName(), "src", "main", "webapp", "resource"));
        try {
            copyResources("common", dirs);
            copyResources("frame", dirs);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected synchronized void mainPage(String jspPath) {
        if (isCreateMainPage) return;
        String db = treeItem.getValue().getData().toString();
        TableInfo tableInfo = DbInfoFactory.getInstance().get(treeItem.getValue().getParent().getId() + "_" + db);

        isCreateMainPage = true;
    }

    public String getProjectName() {
        return "web";
    }

    private void copyResources(String srcDir, List<String> dirs) throws IOException {
        String root = FileUtil.getSourceRoot();
        Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(srcDir);
        String srcFile = urls.nextElement().getFile();
        CopyDirUtil.copyResourceDir(srcFile, root, dirs);
    }
}
